package com.yubest.demo.service.impl;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.yubest.demo.anno.JsonField;
import com.yubest.demo.service.JsonStrategy;

import java.io.IOException;

/**
 * @author huangweiyu
 * @version V1.0
 * @date 21:54
 **/
public class MyJsonSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    private JsonStrategy strategy;

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeObject(strategy.to(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        JsonField annotation = property.getAnnotation(JsonField.class);
        if (null != annotation) {
            this.strategy = annotation.strategy().newStrategy();
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }

}
